package com.hmdp.utils;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;


//redisId生成器
@Component
public class RedisIdWorker {
    private StringRedisTemplate stringRedisTemplate;

    //2022.1.1 0时0分到现在的秒数作为开始时间戳
    public static final long BEGIN_TIMESTAMP = 1640995200L;
    public static final int COUNT_BITS = 32;

    public RedisIdWorker(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    public Long nextId(String keyPrefix) {
        //获取时间戳
        LocalDateTime now = LocalDateTime.now();
        long nowSeconds = now.toEpochSecond(ZoneOffset.UTC);
        long timeStamp=nowSeconds-BEGIN_TIMESTAMP;
        //生成序列号
        String date = now.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
        Long count = stringRedisTemplate.opsForValue().increment("icr:" + keyPrefix + ":" + date);
        return timeStamp<<COUNT_BITS|count;
    }

    public static void main(String[] args) {
        LocalDateTime ofTime = LocalDateTime.of(2022, 1, 1, 0, 0);
        long seconds = ofTime.toEpochSecond(ZoneOffset.UTC);
        System.out.println(seconds);
    }
}
